/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package vn.ac.aptech.fat1.c0910g.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import vn.ac.aptech.fat1.c0910g.dao.UserDAO;
import vn.ac.aptech.fat1.c0910g.entity.User;

/**
 *
 * @author NDC
 */
public class UserDaoImpl implements UserDAO {
    private Connection conn;

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public UserDaoImpl() {
    }

    public UserDaoImpl(Connection con) {
        this.conn = con;
    }

    public boolean createUser(User u) throws Exception {
        try {
            PreparedStatement stm = conn.prepareStatement("INSERT INTO User VALUES(?,?)");
            stm.setString(1, u.getUsername());
            stm.setString(2, u.getPassword());

            int k = stm.executeUpdate();

            if(k>0){
                return true;
            }
            return false;
        } catch (Exception e) {
            throw e;
        }
    }

    public boolean updateUser(User u) throws Exception {
        try {
            PreparedStatement stm = conn.prepareStatement("UPDATE User SET username=?, password=? WHERE id=?");
            stm.setString(1, u.getUsername());
            stm.setString(2, u.getPassword());
            stm.setInt(3, u.getId());
           
            int k = stm.executeUpdate();

            if(k>0){
                return true;
            }
            return false;
        } catch (Exception e) {
            throw e;
        }
    }

    public boolean deleteUser(User u) throws Exception {
        try {
            PreparedStatement stm = conn.prepareStatement("DELETE FROM User WHERE id=?");
            stm.setInt(1, u.getId());
            
            int k = stm.executeUpdate();

            if(k>0){
                return true;
            }
            return false;
        } catch (Exception e) {
            throw e;
        }
    }

    public User doLogin(String username, String password) throws Exception {
        try {
            PreparedStatement stm = conn.prepareStatement("SELECT * FROM Users WHERE Username=? AND Password=?");
            stm.setString(1, username);
            stm.setString(2, password);
            
            ResultSet rs = stm.executeQuery();

            if(rs.next()){
                User u = new User();
                u.setUsername(rs.getString("Username"));
                u.setPassword(rs.getString("Password"));

                return u;
            }
            return null;
        } catch (Exception e) {
            throw e;
        }
    }
}
